<template>
    <el-upload :class="{ hide_box: !state.showUpload }" :file-list="state.fileList" action="#"
        :http-request="handleUploadImage" list-type="picture-card" :before-upload="beforeAvatarUpload"
        :on-preview="handlePictureCardPreview" :disabled="!state.showUpload || props.disabled" :on-remove="handleRemove"
        :limit="limit">
        <el-icon>
            <Plus />
        </el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible" title="图片预览">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ref, computed, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { uploadFile } from '/@/api/index'
import type { UploadProps, UploadUserFile } from 'element-plus'

const props = defineProps({
    modelValue: {
        type: String,
        default: () => '',
    },
    width: {
        type: Number,
        default: () => 150
    },
    height: {
        type: Number,
        default: () => 150
    },
    limit: {
        type: Number,
        default: () => 1
    },
    disabled: {
        type: Boolean,
        default: () => false
    }
});

const state = reactive<any>({
    fileList: <any>[],
    showUpload: false,
})

state.fileList = computed(() => {
    let files = <any>[]
    if (props.modelValue) {
        const arr = props.modelValue.split(',')
        const len = arr.length > props.limit ? props.limit : arr.length;
        for (let i = 0; i < len; i++) {
            files.push({ name: '', url: '/api' + arr[i] })
        }
    }
    return files;
})

const emit = defineEmits(["update:modelValue"])

state.showUpload = computed(() => {
    return state.fileList.length < props.limit;
});

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片格式不正确!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片尺寸不能大于2M!')
        return false
    }
    return true
}

const handleUploadImage = async (param: any) => {
    let formData = new FormData();
    formData.append("file", param.file);
    const rest = await uploadFile(formData);
    if (rest) {
        ElMessage.success('上传成功！');
        const value = props.modelValue ?  props.modelValue + ',' + rest.data[0] : rest.data[0]
        emit('update:modelValue', value)
    } else {
        ElMessage.error('上传失败！');
    }
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    const url = uploadFile.url
    let arr = props.modelValue.split(',');
    for(let i = 0; i < arr.length; i++) {
        if(url!.indexOf(arr[i]) > -1) {
            arr = arr.splice(i, 1);
        }
    }
    emit('update:modelValue', arr.join(','))
    // console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
</script>
  
<style lang="scss" scoped>
.hide_box :deep(.el-upload--picture-card) {
    display: none;
}
</style>